#coding=utf-8

import os
import sys
reload(sys)
sys.setdefaultencoding('utf-8')

import xlrd
from pymongo import MongoClient
from pymongo.errors import ConnectionFailure, AutoReconnect, DuplicateKeyError
from XMLGenerator.T_XML import T_XML
from ExcelReader.RowGenerator import *

def error(msg):
    sys.stderr.write('%s\n'%msg)
    raise Exception(msg)

def insert_rec(rec, col, ignore_error=True, upsert=False):
    try:
        if upsert:
            _id = rec['_id']
            rec.pop('_id')
            col.update_one({'_id':_id}, {'$set':rec}, upsert=True)
        else:
            col.insert_one(rec)
    except DuplicateKeyError as e:
        error('rec Alread Exist! rec=%s'%(rec))
        if not ignore_error:
            raise

    return True

def _print_first_table_name(data):
    #打印第一个工作表的名字
    print '####  %s   ###'%data.sheet_names()[0]

class SpecialEmployeeRowGenerator(BaseRowGenerator):
    def __init__(self, row_value):
        super(SpecialEmployeeRowGenerator, self).__init__(row_value)

    #提取出来后返回True，否则返回False
    def collect_useful_data(self):

        try:

            self.special_clause_id = self.inited_row_value[6]
            self.special_clause_detail = self.inited_row_value[7]

        except Exception,e:
            error('ERROR:Read_Row_DataError!!!!!!!!!!')
            self.isCollected = False

        self.isCollected = True

    def update_useful_data(self):
        if type(self.special_clause_detail) ==  str:
            self.special_clause_detail =T_XML(self.special_clause_detail).t_xml()


    def __str__(self):
        return ' '.join(self.inited_row_value)


def read_special_clauses_excel_file(file_path):
    isExist = os.path.exists(file_path)
    if not isExist:
        error('ERROR:%s该文件不存在'%file_path)
        return
    data = xlrd.open_workbook(file_path)

    _print_first_table_name(data)
    if len(data.sheets()) < 2:
        error("ERROR:%是该文件中没有员工手册特殊条款表" % file_path)
        return

    table = data.sheets()[1]

    mongo_client = MongoClient(host='127.0.0.1', port=27017, document_class=dict, tz_aware=None, connect=None)
    db = mongo_client["CLAUSES"]
    col = db["special_clauses"]

    upsert_all_successful = True

    for row_index in range(2,table.nrows):
        row_value = table.row_values(row_index)
        special_row = SpecialEmployeeRowGenerator(row_value)
        if special_row.isCollected == False:
            error(msg)
            continue
        special_row.update_useful_data()
        if special_row.special_clause_detail:
            print special_row.special_clause_id, special_row.special_clause_detail
            result = insert_rec({"_id":special_row.special_clause_id, "content":special_row.special_clause_detail}, col, ignore_error=True, upsert=True)
            if result is None:
                upsert_all_successful = False
    mongo_client.close()
    return upsert_all_successful

if __name__ == "__main__":

    upsert_all_successful = read_special_clauses_excel_file('Contract/all_clause.xlsx')
    if not upsert_all_successful:
        error("ERROR: 数据库更新插入时出现失败情况")
